package com.zxkj.ssm.weixin.shop.http.executor;
import  static com.zxkj.ssm.weixin.shop.basic.Basic.notEmpty;
import com.zxkj.ssm.weixin.shop.exception.WxErrorException;
import com.zxkj.ssm.weixin.shop.handler.Utf8ResponseHandler;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 *@Author 中芯信息科技
 *@Date 2018/7/11 9:11
 *@Description 简单的POST请求执行器，请求的参数是Map 返回的结果也是String
 *@Version
 */
public class SimpPostNameValuePairRequestExecutor  implements RequestExecutor<String,Map<?,?>>{
    @Override
    public String execute(CloseableHttpClient httpclient, HttpHost httpProxy, String url, Map data) throws WxErrorException, IOException {
        try{
                HttpPost httpPost = new HttpPost();
                httpPost.setURI(new URI(url));
                if (httpProxy != null) {
                    RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
                    httpPost.setConfig(config);
                }
                if(notEmpty(data)){
                    //设置参数
                    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                    for (Iterator iter = data.keySet().iterator(); iter.hasNext();) {
                        String name = (String) iter.next();
                        String value = String.valueOf(data.get(name));
                        nvps.add(new BasicNameValuePair(name, value));
                    }
                    httpPost.setEntity(new UrlEncodedFormEntity(nvps, Charset.forName("UTF-8")));
                    try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
                        return Utf8ResponseHandler.INSTANCE.handleResponse(response);
                    } finally {
                        httpPost.releaseConnection();
                    }
                }
                }catch (URISyntaxException e){
                    throw new WxErrorException("请求数据不能为空!");
                }
                    return null;
                }
}
